/*
 * FfMediaInfo.cpp
 *
 *  Created on: 2023年7月5日
 *      Author: terry
 */

#include "FfMediaInfo.h"
#include <errno.h>
#include "TSafeStr.h"

//extern "C" __declspec(dllexport) int add1(int a, int b);
//
//int add1(int a, int b)
//{
//	return a + b;
//}
//
//extern "C" __declspec(dllexport) void add2(int a, int b, int* c);
//
//void add2(int a, int b, int* c)
//{
//	*c = a + b;
//}


/*
extern "C" DLLEXPORT int ff_getMediaInfo(const char* filepath, FfMediaFormat* fmt, int* frameCount)
{
	return 0;
}


int ff_getFrameRate(const char* filepath, double* framerate)
{
	*framerate = 13.2;
	return 0;
}

*/


#include "FfmpegMediaReader.h"

int  ff_getMediaInfo(const char* filepath, FfMediaFormat* fmt, int* frameCount)
{
	if (!filepath || !fmt)
	{
		return EINVAL;
	}

	FfmpegMediaReader reader;
	int ret = reader.open(filepath, "");
	if (ret != 0)
	{
		return ret;
	}

	UMediaFormat format;
	reader.getFormat(format);

	fmt->bframe = reader.getBFrame();

	fmt->duration = format.m_duration;

	fmt->codec = format.m_codec;
	fmt->width = format.m_width;
	fmt->height = format.m_height;
	fmt->bitrate = format.m_bitrate;
	fmt->profile = format.m_profile;
	fmt->level = format.m_level;
	fmt->gop = format.m_gop;

	fmt->audioCodec = format.m_audioCodec;
	fmt->channels = format.m_channels;
	fmt->samplerate = format.m_sampleRate;
	fmt->audioBitrate = format.m_audioBitrate;
	fmt->audioProfile = format.m_audioProfile;

	comn::copyStr(fmt->fmtName, reader.getFormatName());

	//fmt->framerate = format.m_framerate;
	fmt->duration = format.m_duration;
	fmt->videoDuration = format.m_videoDuration;

	int64_t videoDuration = 0;
	if (format.m_duration <= 0)
	{
		int videoCount = 0;
		fmt->framerate = reader.countFrameRate(&videoCount, &videoDuration);

		if (frameCount)
		{
			*frameCount = videoCount;
		}

		fmt->videoDuration = videoDuration / 1000;
	}
	else
	{
		fmt->framerate = reader.countFrameRate(frameCount, &videoDuration);
	}

	reader.close();

	return 0;
}

int ff_getFrameRate(const char* filepath, double* framerate)
{
	if (!framerate)
	{
		return EINVAL;
	}

	FfMediaFormat fmt = FfMediaFormat();
	int ret = ff_getMediaInfo(filepath, &fmt, nullptr);
	if (ret == 0)
	{
		*framerate = fmt.framerate;
	}
	return ret;
}

int ff_getVideoFrameInfo(const char* filepath, double* framerate, int* duration, int* frameCount)
{
	int videoCount = 0;

	FfMediaFormat fmt = FfMediaFormat();
	int ret = ff_getMediaInfo(filepath, &fmt, &videoCount);
	if (ret == 0)
	{
		if (framerate)
		{
			*framerate = fmt.framerate;
		}

		if (duration)
		{
			*duration = fmt.duration;
		}
		
		if (frameCount)
		{
			*frameCount = videoCount;
		}
	}
	return ret;
}